<template>
  <div class="pa-5 bg-white">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电表名称" prop="meterName">
        <el-input
          v-model="queryParams.meterName"
          placeholder="请输入电表名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期" prop="scheduleDate">
        <el-input
          v-model="queryParams.scheduleDate"
          placeholder="请输入日期"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="importTemplate"
        >下载模板
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleAdd"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="electricityConsumptionList" >
      <el-table-column label="序号" align="center"  type="index"/>
      <el-table-column label="电表名称" align="center" prop="meterName"/>
      <el-table-column label="线体名称" align="center" prop="lineName"/>
      <el-table-column label="日期" align="center" prop="scheduleDate"/>
      <el-table-column label="表码量" align="center" prop="consumptionTotal"/>
      <el-table-column label="电量" align="center" prop="consumption"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--          >删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="openUpload" width="1000px" append-to-body>
      <el-form ref="form" :model="form" v-loading="loadingDialog" label-width="80px">

        <el-form-item label="上传文件">
          <el-upload
            ref="upload"
            class="upload-demo"
            name="file"
            limit="1"
            accept=" .xls, .xlsx"
            :headers="headers"
            :action="fileAction"
            :data="uploadObjs"
            :before-upload="beforeUpload"
            :on-success="handleFileSuccess"
            :on-remove="handleRemove"
            :file-list="form.fileList"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="submitFlag" @click="submit">确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>

    </el-dialog>
    <!-- 添加或修改电能耗信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="线体名称" prop="lineName">
          <el-input v-model="form.lineName"  :disabled="true"  placeholder="请输入线体名称" />
        </el-form-item>
        <el-form-item label="电表名称" prop="meterName">
          <el-input v-model="form.meterName"  :disabled="true" placeholder="请输入电表名称" />
        </el-form-item>
        <el-form-item label="日期" prop="scheduleDate">
          <el-input v-model="form.scheduleDate" :disabled="true" placeholder="请输入日期" />
        </el-form-item>
        <el-form-item label="表码量" prop="consumptionTotal">
          <el-input v-model="form.consumptionTotal" type="number"  placeholder="请输入表码量" />
        </el-form-item>
        <el-form-item label="电量" prop="consumption">
          <el-input v-model="form.consumption" type="number" placeholder="请输入电量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import {
        addElectricityConsumption,
        delElectricityConsumption,
        exportElectricityConsumption,
        getElectricityConsumption,
        listElectricityConsumption,
        updateElectricityConsumption,
        importTemplate
    } from "@/api/idss/electricityEntry/electricityConsumption";
    import pagination from "@/components/pagination";
    import { getToken } from '@/utils/auth'
    import moment from "moment";
    export default {
        name: "ElectricityConsumption",
        components: {pagination},
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 电能耗信息表格数据
                electricityConsumptionList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNo: 1,
                    pageSize: 10,
                    meterId: null,
                    meterName: null,
                    scheduleDate: null,
                    consumptionTotal: null,
                    consumption: null
                },
                // 表单参数
                form: {},
                // 表单校验
                rules: {

                    consumptionTotal: [{required: true, message: "表码量不能为空", trigger: "blur"}],
                    consumption: [{required: true, message: "电量不能为空", trigger: "blur"}],
                },
                openUpload: false,
                fileAction: process.env.VUE_APP_BASE_API + '/idss/electricityBase/importFile',
                prefix: process.env.VUE_APP_BASE_API,
                headers: {Authorization: getToken()},
                uploadObjs: {}
            };
        },
        created() {
            this.getList();
        },
        methods: {
            /** 查询电能耗信息列表 */
            getList() {
                this.loading = true;
                listElectricityConsumption(this.queryParams).then(response => {
                    this.electricityConsumptionList = response.data.listObject;
                    this.total = response.data.itemCount;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    meterId: null,
                    meterName: null,
                    scheduleDate: null,
                    consumptionTotal: null,
                    consumption: null
                };

            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNo = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.queryParams= {
                    pageNo: 1,
                        pageSize: 10,
                        meterId: null,
                        meterName: null,
                        scheduleDate: null,
                        consumptionTotal: null,
                        consumption: null
                }
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length !== 1
                this.multiple = !selection.length
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.openUpload = true;
                this.title = "电能耗数据导入信息";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.ids
                getElectricityConsumption(id).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改电能耗信息";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updateElectricityConsumption(this.form).then(response => {
                                this.$message.success("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addElectricityConsumption(this.form).then(response => {
                                this.$message.success('新增成功')
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$confirm('是否确认删除电能耗信息编号为"' + ids + '"的数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return delElectricityConsumption(ids);
                }).then(() => {
                    this.getList();
                    this.$message.success("删除成功");
                })
            },
            /** 导出按钮操作 */
            handleExport() {
                const queryParams = this.queryParams;
                this.$confirm('是否确认导出所有电能耗信息数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return exportElectricityConsumption(queryParams);
                }).then(response => {
                    this.download(response.msg);
                })
            },
            /** 导出按钮操作 */
            handleExport() {
                const queryParams = this.queryParams;
                this.$confirm('是否确认导出所有电基础信息数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return exportElectricityBase(queryParams);
                }).then(response => {
                    this.download(response.msg);
                })
            },
            beforeUpload(file) {
                // 限制文件最大不能超过 300M
                const isLt2M = file.size / 1024 / 1024 < 10

                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 10MB!')
                }
                return isLt2M
            },
            submit() {
                this.loadingDialog = true
                this.$refs.upload.submit()
                this.submitFlag = true
            },
            handleRemove(file, fileList) {
                for (var i = 0; i < this.form.fileList.length; i++) {
                    if (file.response) {
                        if (this.form.fileList[i] == file.response.fileUrl) {
                            //delete
                            this.form.fileList.splice(i, 1)
                        }
                    } else {
                        if (this.form.fileList[i].url == file.url) {
                            this.form.fileList.splice(i, 1)
                        }
                    }
                }

            },
            handleFileSuccess(res, file) {
                this.loadingDialog = false
                this.$alert(res.data, '导入结果', {dangerouslyUseHTMLString: true})
                this.submitFlag = false
                this.reset()
            },
            /** 下载模板操作 */
            importTemplate() {

                importTemplate().then(res => {
                    const _exportFileUrl = window.URL.createObjectURL(
                        new Blob([res], {
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,charset=utf-8'
                        })
                    )
                    const _link = document.createElement('a')
                    const _curDate = moment(new Date()).format('YYYYMMDD')
                    _link.download = `电能耗模板_${_curDate}`
                    _link.href = _exportFileUrl
                    _link.click()
                    window.URL.revokeObjectURL(_exportFileUrl)

                })
            },
        }
    };
</script>
